package streamforce.crypto.cloud.subscriber;

import java.util.concurrent.ThreadPoolExecutor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import streamforce.Stat;
import streamforce.crypto.KPAbe;
import streamforce.crypto.cloud.EPCloud;
import streamforce.crypto.cloud.EPCloudServer;
import streamforce.crypto.cloud.TimeTuple;
import streamforce.crypto.cloud.Tuple;
import streamforce.crypto.event.Ciphertext;
import streamforce.crypto.event.TransformedCTEventAll;
import streamforce.crypto.policies.Policy;

//for query: select price from StockEvent(cond)
//assuming that the cryptohandler has been initialized
public class CloudSelectPrice extends Policy{
	final Log log = LogFactory.getLog(CloudSelectPrice.class);
	
	int policyId;//the same as userId
	Stat stat,statTuple; 	
	public CloudSelectPrice(int pi, KPAbe ch){
		super(ch);
		this.policyId = pi;
		this.stat = new Stat("nTransformed");
		this.statTuple = new Stat("nTuples"); 
	}
	
	public int getPolicyId(){
		return this.policyId;
	}
	
	public  void update(int timestamp, int hour, int stockId, Ciphertext ct) {		
		if (ct != null) {
			TimeTuple tt = EPCloudServer.tupleTime.get(new Tuple(stockId, timestamp)); 
			if (tt.getCount()==0)
				this.statTuple.update(); 			
			tt.increaseCount();
			
			byte[] ciphertext = ct.getCipher();
			long start = System.currentTimeMillis();
			byte[] oct = this.cryptoHandler.extractOriginalCipher(
					stockId, ciphertext);
			byte[] tct = this.cryptoHandler.transform_simple(ciphertext,
					this.streamId, this.userId);
			byte[][] originals = new byte[1][oct.length];
			byte[][] transforms = new byte[1][tct.length];
			originals[0] = oct; transforms[0] = tct;
			long end = System.currentTimeMillis();
			log.debug("transformation time = " + (end - start)+" for stock Id = "+stockId);

			// then construct and send another event
			TransformedCTEventAll cte = new TransformedCTEventAll(
					this.policyId, timestamp, hour, stockId, originals, transforms,
					TransformedCTEventAll.SELECT_ALL);
			this.stat.update();						
			EPCloud.getEPServiceProvider().getEPRuntime().sendEvent(cte);
		}
	}
}
